package com.zf.rabbitmq.producer.topic;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Topic 类型交换机，
 * 使用 AmqpAdmin API声明
 */
@Component
public class TopicExchangeConfig implements InitializingBean {
    public static final String testTopicExchangeName = "test_topic_exchange";
    public static final String testTopicQueue1Name = "test_topic_queue1";
    public static final String testTopicQueue2Name = "test_topic_queue2";
    public static final String testTopicRouteKey1 = "topic.*";
    public static final String testTopicRouteKey2 = "#.item";

    @Autowired
    private AmqpAdmin amqpAdmin;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 声明交换机
        Exchange exchange = ExchangeBuilder.topicExchange(testTopicExchangeName).durable(true).build();
        amqpAdmin.declareExchange(exchange);

        // 声明队列
        Queue queue1 = QueueBuilder.durable(testTopicQueue1Name).build();
        Queue queue2 = QueueBuilder.durable(testTopicQueue2Name).build();
        amqpAdmin.declareQueue(queue1);
        amqpAdmin.declareQueue(queue2);

        // 声明绑定
        Binding binding1 = BindingBuilder.bind(queue1).to(exchange).with(testTopicRouteKey1).noargs();
        Binding binding2 = BindingBuilder.bind(queue2).to(exchange).with(testTopicRouteKey2).noargs();
        amqpAdmin.declareBinding(binding1);
        amqpAdmin.declareBinding(binding2);
    }
}
